<?php
/**
 * Created by PhpStorm.
 * User: Jiarui
 * Date: 2015/10/11
 * Time: 0:52
 */

namespace Admin\Controller;
use Think\Controller;
use Think\Exception;
use Think\Log;

class RouteController extends BaseController  {

    public function _initialize(){
        parent::_initialize();

        $fpath = dirname(__FILE__);
        $fps = explode(DIRECTORY_SEPARATOR,$fpath);
        $len = count($fps);
        unset($fps[$len-1]);
        unset($fps[$len-2]);
        unset($fps[$len-3]);

        define('__PUBLIC__',implode(DIRECTORY_SEPARATOR,$fps).DIRECTORY_SEPARATOR.'Public');

    }

    public function listPage(){

        $this->display();
        
    }

    public function addRoutePage(){
        $this->display();
    }

    public function getRouteList(){
        $title = I('title/s');
        $type = I('type/d');
        $status = I('status/d');

        $route_model = D('Route');
        try {
            $data = $route_model->getRoute($title, $type,$status);
        }catch (Exception $e){
            $this->ajaxReturn(array('state'=>'0','show'=>0));
        }
        $data->state = 1;
        $this->ajaxReturn($data);

    }

    public function getRouteForSet(){

        $title = I('title/s');
        $type = 0;
        $status = 1;

        $route_model = D('Route');
        try {
            $data = $route_model->getRoute($title, $type,$status,6);
        }catch (Exception $e){
            $this->ajaxReturn(array('state'=>'0','show'=>0));
        }
        $data->state = 1;
        $this->ajaxReturn($data);

    }

    public function addRoute(){
        $data['name'] = I('post.name',null);
//        $data['startTime'] = I('post.start_time',null);
//        $data['endTime'] = I('post.end_time',null);
        $data['members'] = I('post.num',null);
        $data['company'] = I('post.company',null);
        $data['status'] = I('post.status',0);
        //$data['imageName'] = I('post.image_name');
        $data['text'] = I('post.text',null);
        $data['sort'] = I('post.sort/d',0);
        $data['model'] = I('post.model/d',0);
        try {
            D('Route')->addRoute($data);
        }catch (Exception $e){
            Log::write(json_encode($e->getMessage),'ERR');
        }
        $this->ajaxReturn('success');
    }

    public function uploadImg(){


        @set_time_limit(5 * 60);

        $targetDir = __PUBLIC__.DIRECTORY_SEPARATOR.'uploads_tmp';

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds

        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

        $targetDir = $targetDir.DIRECTORY_SEPARATOR.'route';


        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }

//        $fileName .= time();

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;

        if ($cleanupTargetDir) {

            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {

                $this->ajaxReturn($targetDir.'---'.$dir.'{"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');

            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }


        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        $eName = I('post.id1').time();

        $fileP = $targetDir.DIRECTORY_SEPARATOR.$eName;

        rename("{$filePath}_{$chunk}.parttmp", "{$fileP}_{$chunk}.part");

        $this->ajaxReturn("{$eName}_{$chunk}.part");

    }

    public function deleteRoute(){

        $ids = I('get.ids');

        if(D('Route')->deleteRoute($ids)){

            $this->ajaxReturn('success');

        }else{

            $this->ajaxReturn('fail');

        }

    }

    public function routeMessage(){

        $id = $_GET['id'];

        $result = D('Route')->getRouteById($id);

        $this->assign('route',$result);

        $this->display();

    }

    public function editRoute(){

        $id = I('get.id/d');

        if($id<=0){
            return ;
        }

        $routes = D('Route')->getRouteById($id);

        foreach($routes as $key => $value){
            $this->assign($key,$value);
        }

        $this->assign('id',$id);

        $this->display();

    }

    public function editRouteSave(){

        $id = I('post.id/d');

        if($id<=0){
            return;
        }

        $name = I('post.name/s');

        $exist = M('route')->where(array('id'=>$id))->select();

        if($exist == null || empty($exist)){

            $this->ajaxReturn('noExist');

        }

        $data = array(
            'id'         =>  $id,
            'name'      =>  $name,
//            'startTime' =>  I('post.start_time'),
            'endTime'   =>  date('Y-m-d H:i:s',time()),
            'members'=>  I('post.num/d'),
            'text'       =>  I('post.text/s'),
            'company'  =>  I('post.orgnazition/s'),
            'status' =>I('post.status/d'),
            'sort' =>I('post.sort/d'),
            'model' => I('post.model/d',0),
            'img_url'=>I('post.image_name/s')
        );


        try {
            D('Route')->update($data);
        }catch (Exception $e){
            Log::write(json_encode($e->getMessage()),'ERR');
            $this->ajaxReturn('error');
        }

        $this->ajaxReturn('success');

    }

}